export interface LoginResponse {
  access_token: string
  token_type: string
  expires_in: number
}

// 获取访问令牌
export const getAuthToken = (): string | null => {
  return localStorage.getItem('access_token')
}

// 获取令牌类型
export const getTokenType = (): string | null => {
  return localStorage.getItem('token_type')
}

// 获取令牌过期时间
export const getTokenExpiration = (): number | null => {
  const expiresIn = localStorage.getItem('expires_in')
  const loginTime = localStorage.getItem('login_time')

  if (!expiresIn || !loginTime) return null

  return parseInt(loginTime) + (parseInt(expiresIn) * 1000)
}

// 检查令牌是否过期
export const isTokenExpired = (): boolean => {
  const expirationTime = getTokenExpiration()

  if (!expirationTime) return true

  return Date.now() > expirationTime
}

// 保存认证信息
export const saveAuthToken = (data: LoginResponse): void => {
  localStorage.setItem('access_token', data.access_token)
  localStorage.setItem('token_type', data.token_type)
  localStorage.setItem('expires_in', data.expires_in.toString())
  localStorage.setItem('login_time', Date.now().toString())
}

// 清除认证信息
export const clearAuthToken = (): void => {
  localStorage.removeItem('access_token')
  localStorage.removeItem('token_type')
  localStorage.removeItem('expires_in')
  localStorage.removeItem('login_time')
}

// 检查用户是否已认证
export const isAuthenticated = (): boolean => {
  const token = getAuthToken()

  if (!token) {
    return false
  }

  if (isTokenExpired()) {
    clearAuthToken()
    return false
  }

  return true
}

// 获取完整的 Authorization header
export const getAuthHeader = (): string | null => {
  const token = getAuthToken()
  const tokenType = getTokenType()

  if (!token || !tokenType) return null

  return `${tokenType} ${token}`
}

// 获取剩余有效时间（秒）
export const getTokenRemainingTime = (): number => {
  const expirationTime = getTokenExpiration()

  if (!expirationTime) return 0

  const remaining = Math.floor((expirationTime - Date.now()) / 1000)
  return Math.max(0, remaining)
}

// 登出函数
export const logout = (): void => {
  clearAuthToken()
  // 可以在这里添加其他登出逻辑
  console.log('用户已登出')
}

// 刷新令牌前的检查（可用于自动刷新逻辑）
export const shouldRefreshToken = (): boolean => {
  const remainingTime = getTokenRemainingTime()
  // 如果剩余时间少于5分钟，建议刷新
  return remainingTime > 0 && remainingTime < 300
}
